<template>
  <div class="update-photo">
    <img class="image" :src="image" ref="image" />
    <van-nav-bar
      class="toolbar"
      left-text="取消"
      right-text="确认"
      @click-left="$emit('close')"
      @click-right="onConfirm"
    />
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { mapState } from 'vuex'
export default {
  components: {},
  props: {
    file: {
      required: true
    }
  },
  data () {
    return {
      image: window.URL.createObjectURL(this.file),
      cropper: null
    }
  },
  computed: {
    ...mapState(['user'])
  },
  watch: {},
  created () {},
  mounted () {
    this.user.photo = process.env.VUE_APP_API_BASE_URL + this.user.photo
    const image = this.$refs.image
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true
    })
  },
  methods: {
    getCroppedCanvas () {
      return new Promise(resolve => {
        this.cropper.getCroppedCanvas().toBlob(file => {
          resolve(file)
        })
      })
    },

    async onConfirm () {
      this.$toast.loading({
        message: '保存中',
        forbidclick: true,
        duration: 0
      })

      const file = await this.getCroppedCanvas()
      const fd = new FormData()
      fd.append('file', file)
      await this.$http.post(`api/file/upload/${this.user.username}`, fd).then(({ data: res }) => {
        if (res.code === 0) {
          const url = res.data
          this.$http.put('api/user/logoInfo', {
            data: {
              photo: url,
              username: this.user.username
            }
          }).then(({ data: res }) => {
            if (res.code === 0) {
              const data = {
                ...this.user,
                photo: process.env.VUE_APP_API_BASE_URL + url
              }
              this.$emit('update-photo', window.URL.createObjectURL(file))
              this.$emit('close')
              this.$store.commit('setUser', data)
              this.$toast.success('保存成功')
            } else {
              this.$toast.fail('修改失败')
            }
          })
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
.update-photo {
  height: 100%;
}

.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #000;
}

/* Ensure the size of the image fit the container perfectly */
.image {
  display: block;

  /* This rule is very important, please don't ignore this */
  max-width: 100%;
}
</style>
